package com.gzdh.tang.dishrecognition.listener;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.gzdh.tang.comm.util.RedisUtil;
import com.gzdh.tang.config.weixin.WXPayUtils;
import com.gzdh.tang.modu.entity.MacMainpOrder;
import com.gzdh.tang.modu.service.MacMainpOrderService;
import com.gzdh.tang.modu.service.ReserveService;
import com.wechat.pay.java.core.Config;
import com.wechat.pay.java.core.RSAPublicKeyConfig;
import com.wechat.pay.java.service.refund.RefundService;
import com.wechat.pay.java.service.refund.model.AmountReq;
import com.wechat.pay.java.service.refund.model.CreateRequest;
import com.wechat.pay.java.service.refund.model.Refund;
import com.wechat.pay.java.service.refund.model.Status;
import lombok.extern.slf4j.Slf4j;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.stream.MapRecord;
import org.springframework.data.redis.connection.stream.RecordId;
import org.springframework.data.redis.stream.StreamListener;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import javax.annotation.PostConstruct;
import java.math.BigDecimal;
import java.util.Map;

/**
 * @author ：zz
 * @date ：Created in 2022/5/19 10:15
 * @description：消费监听，不自动ack
 */
@Slf4j
@Component
public class ConsumeListener1 implements StreamListener<String, MapRecord<String, String, String>> {

    @Autowired
    private RedisUtil redisUtil;

    private static ConsumeListener1 consumeListener1;

    @Autowired
    private ReserveService reserveService;

    @Autowired
    private MacMainpOrderService macMainpOrderService;

    @PostConstruct
    public void init() {
        consumeListener1 = this;
        consumeListener1.redisUtil = this.redisUtil;
        consumeListener1.reserveService = this.reserveService;
        consumeListener1.macMainpOrderService = this.macMainpOrderService;
    }

    @Override
    public void onMessage(MapRecord<String, String, String> message) {
        String stream = message.getStream();
        RecordId id = message.getId();
        Map<String, String> map = message.getValue();
        System.out.println("开始出路i");
        log.info("[不自动ack] group:[group-a] consumerName:[{}] 接收到一个消息 stream:[{}],id:[{}],value:[{}]", stream, id, map);

        log.info("开始处理时间：" + System.currentTimeMillis());

        try {

            log.info("内容" + map.get("orders").replaceAll("\"", ""));
            String tkOrders = map.get("orders").replaceAll("\"", "");
            MacMainpOrder macMainpOrder = macMainpOrderService.getOne(new QueryWrapper<MacMainpOrder>().lambda()
                    .eq(MacMainpOrder::getRefundOrder, tkOrders));

            Config config = new RSAPublicKeyConfig.Builder()
                    .merchantId(WXPayUtils.getMchId())
                    .privateKey(WXPayUtils.getPrivateKey())
                    .merchantSerialNumber(WXPayUtils.getMerchantSerialNumber())
                    .apiV3Key(WXPayUtils.getApiV3Key())
                    .publicKey(WXPayUtils.getMerchantPublicKey())
                    .publicKeyId(WXPayUtils.getMerchantPublicKeyId())
                    .build();

            RefundService service = new RefundService.Builder().config(config).build();
            CreateRequest createRequest = new CreateRequest();

            AmountReq amountReq = new AmountReq();
            amountReq.setRefund(new BigDecimal(macMainpOrder.getAmountPrice()).multiply(new BigDecimal(100)).stripTrailingZeros().longValue());//【退款金额】 退款金额，单位为分，只能为整数，不能超过原订单支付金额。
            amountReq.setTotal(new BigDecimal(macMainpOrder.getAmountPrice()).multiply(new BigDecimal(100)).stripTrailingZeros().longValue());//【原订单金额】 原支付交易的订单总金额，单位为分，只能为整数。
            amountReq.setCurrency("CNY");//退款币种】 符合ISO 4217标准的三位字母代码，目前只支持人民币：CNY。
            createRequest.setAmount(amountReq);
            if (WXPayUtils.getSubmchMode() == 1) {
                createRequest.setSubMchid(WXPayUtils.getSubMchId());
            }
            createRequest.setOutTradeNo(macMainpOrder.getOrders());//【商户订单号】 原支付交易对应的商户订单号，与transaction_id二选一
            createRequest.setOutRefundNo(macMainpOrder.getRefundOrder());
            Refund refund = service.create(createRequest);
            if (refund.getStatus() == Status.SUCCESS) {
                System.out.println("退款成功");
                macMainpOrder.setRefundState(1);
            } else if (refund.getStatus() == Status.ABNORMAL || refund.getStatus() == Status.CLOSED) {
                macMainpOrder.setRefundState(-1);
            }
            macMainpOrder.setRefundMsg(refund.toString());
            macMainpOrderService.updateById(macMainpOrder);

        } catch (RuntimeException e) {
            e.printStackTrace();
        }

        log.info("开始结束时间：" + System.currentTimeMillis());

        consumeListener1.redisUtil.ack(stream, "group-a", id.getValue());
        consumeListener1.redisUtil.del2(stream, id.getValue());
    }
}
